package com.mina.server;

import com.mina.constant.Constants;
import com.mina.model.Message;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务器端的消息处理器
 */
public class MinaServerHandler extends IoHandlerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(MinaServerHandler.class);


    @Override
    public void sessionOpened(IoSession session) throws Exception {
        LOGGER.info("welcome client: {}", session.getRemoteAddress());
        Constants.session1 = session;
    }
    //会话关闭

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        LOGGER.info("session closed.");
    }

    //接收消息
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        Message msg = (Message)message;
        LOGGER.info("收到客户端发来的消息：{}", msg);
        //向客户端发送消息对象
        session.write(msg);
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        LOGGER.error("连接断开.");
    }
}